import axios from 'axios';

// post请求
export function post(
  type,
  requestUrl,
  data,
  config = {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  }
) {
  const resType = {
    form() {
      let relParams = {};
      var fd = new FormData();
      data.forEach(params => {
        if (params.key !== '') {
          fd.append(params.key, params.value);
        }
      });
      const response = resPost('post', requestUrl, fd, {}, config);
      return response;
    },
    json() {
      const params = JSON.parse(data);
      const response = resPost('post', requestUrl, { ...params });
      return response;
    },
  };
  return resType[type].call(this);
}

// get请求
export function get(requestUrl, data, config = {}) {
  let relParams = {};
  data.forEach(params => {
    if (params.key !== '') {
      relParams[params.key] = params.value;
    }
  });
  const response = resPost('get', requestUrl, {}, { ...relParams });
  return response;
}

// 请求
export function resPost(type, url, data = {}, params = {}, config = {}) {
  const response = axios({
    method: type,
    url,
    data,
    params,
    config,
  });
  return response;
}

//请求数据类型判断
export function setResData(response) {
  if (response.data) {
    if (response.data instanceof Array) {
      return response.data;
    } else if (response.data instanceof Object) {
      const comArray = setResponseData(response.data);
      return comArray;
    }
  } else {
    return [];
  }
}

// 数据处理
export function setResponseData(data) {
  let comArray = [],
    comObejct = {},
    isComObject = false;

  for (let [key, value] of Object.entries(data)) {
    if (value instanceof Object) {
      comArray.push(value);
    } else if (value instanceof Array) {
      comArray.push(value.toString());
    } else {
      isComObject = true;
      comObejct[key] = value;
    }
  }
  if (isComObject) {
    comArray.push(comObejct);
  }
  return comArray;
}
